package com.travelbid.common;


import java.io.UnsupportedEncodingException;
import java.util.*;
import javax.servlet.http.HttpServletRequest;
import org.hibernate.HibernateException;
import org.hibernate.Query;



public class PagingTool {
	
	
	
	
	public static List getQueryResByPage(Query query, Paging page) throws HibernateException
	{
		/*
		if(page.getPageCount() == -1)
		{
			String hql = query.getQueryString();
			String countStr = "SELECT COUNT(*) from (" + hql + ") as p1";
			Query coutQuery = session.createQuery(countStr);
			
			page.setTotalCount((Integer)coutQuery.uniqueResult());
		}
		*/
		//���ǰҳ�������ҳ��
		if(page.getCurrentPage() > page.getPageCount()){
			page.setCurrentPage(page.getPageCount());
		}
		int start=(page.getCurrentPage() - 1 )* page.getPageSize(); 
		query.setFirstResult(start); 
		query.setMaxResults(page.getPageSize()); 
		return query.list();
	}
	
	/*
	 * ��request�й�����page����
	 */
	public static Paging getPage(HttpServletRequest request){		
		Paging page = new Paging();
		String currentPage = request.getParameter(Paging.PAGE_CURRENT_STR);
		if(currentPage != null){
			page.setCurrentPage(Integer.parseInt(currentPage));
		}
		
		String pgSize = request.getParameter(Paging.PAGE_SIZE_STR);
		if(pgSize != null){
			page.setPageSize(Integer.parseInt(pgSize));
		}
		
		String pageTotal = request.getParameter(Paging.PAGE_TOTAL_STR);
		if(pgSize != null){
			page.setTotalCount(Integer.parseInt(pageTotal));
		}
		
		StringBuffer action = new StringBuffer("");
		int flag = 0;
		for (Enumeration iter = request.getParameterNames(); iter.hasMoreElements();flag++) {
			String element = (String) iter.nextElement();
			if(element.equals(Paging.PAGE_CURRENT_STR)||element.equals(Paging.PAGE_SIZE_STR)||element.equals(Paging.PAGE_TOTAL_STR))
				continue;
			if(flag >= 1)
				action.append("&");
			try {
				action.append(element+"=" + java.net.URLEncoder.encode(request.getParameter(element),"UTF-8"));
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		page.setAction(request.getRequestURI()+"?"+action.toString());
		
		return page;
	}
	
	
	
	

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

}


